package com.example.mediaplayer;

import MediaEntity.MP3Entity;
import MediaEntity.MediaEntity;
import MediaEntity.MediaList;
import javafx.animation.Animation;
import javafx.animation.Interpolator;
import javafx.animation.RotateTransition;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.control.Label;
import javafx.scene.effect.GaussianBlur;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.*;
import javafx.scene.media.AudioSpectrumListener;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaView;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.TextAlignment;
import javafx.stage.DirectoryChooser;
import javafx.stage.Stage;
import javafx.util.Callback;
import javafx.util.Duration;

import java.io.File;
import java.net.URL;
import java.util.*;

public class BottomController implements Initializable {

    public AnchorPane ap;
    public BorderPane rootPane;
    public VBox leftVBox;
    public HBox leftHBox;
    public HBox topHBox;
    public Pane bottomPane;
    public ImageView albumImg;
    public Label songName;
    public Label artistName;
    private boolean sliderFlag = false;
    private boolean folderFlag = false;
    private MediaPlayer musicPlayer;
    private double currentVolume;
    private MediaList musicList;
    private MediaList videoList;
    private long starttime;
    private long endtime;
    private String path;
    private Timer pusher;
    private MediaView Mediaview;
    ObservableList<MediaEntity> observableList;
    RotateTransition rt;
    /**一开始什么也没有指向，为-1*/
    private int currentMusic;
    /**0是音频，1是视频*/
    private int type;
    /**默认是循环0，单曲循环1，随机播放2  */
    private int loopWay;
    @FXML
    public ImageView playBtn;
    public ImageView nextBtn;
    public ImageView previousBtn;
    public ImageView loopMethod;
    public ImageView voice;
    @FXML
    public ComboBox<String> mediaType;
    @FXML
    public ListView<MediaEntity> viewList;
    @FXML
    public Slider volumeSlider;
    public Label currentTime;
    public Label allTime;
    public Slider mediaSlider;
    SpectrumData spectrumData;

    @FXML
    public void click_playBtn() {
        String s;
        if(path == null)
            return;
        if(type!=1){
            if(musicList.size() == 0) return;
            if(musicPlayer == null) {
                currentMusic = 0;
                init_musicPlayer(musicList.getMedia(0));
                viewList.getSelectionModel().select(0);
                //musicPlayer.play();
                s = getClass().getResource("img/stop.png").toExternalForm();
                Image image = new Image(s);
                playBtn.setImage(image);
                return;
            }

            if(musicPlayer.getStatus() == MediaPlayer.Status.PLAYING){
                //修改图标 点击完是暂停状态。
                musicPlayer.pause();
                rt.pause();
                s = getClass().getResource("img/start.png").toExternalForm();
                Image image = new Image(s);
                playBtn.setImage(image);
            }else if (musicPlayer.getStatus() == MediaPlayer.Status.PAUSED){
                //修改图标 点击完是播放状态。
                musicPlayer.play();
                rt.play();
                s = getClass().getResource("img/stop.png").toExternalForm();
                Image image = new Image(s);
                playBtn.setImage(image);
            }}
        else{
            if(videoList.size() == 0) return;
            if(musicPlayer == null) {
                currentMusic = 0;
                init_musicPlayer(videoList.getMedia(0));
                viewList.getSelectionModel().select(0);
                //musicPlayer.play();
                s = getClass().getResource("img/stop.png").toExternalForm();
                Image image = new Image(s);
                playBtn.setImage(image);
                Mediaview=new MediaView(musicPlayer);
                Mediaview.setFitHeight(660);
                Mediaview.setFitWidth(660);
                Mediaview.setY(50);
                ap.getChildren().add(Mediaview);
                return;
            }

            if(musicPlayer.getStatus() == MediaPlayer.Status.PLAYING){
                //修改图标 点击完是暂停状态。
                musicPlayer.pause();
                s = getClass().getResource("img/start.png").toExternalForm();
                Image image = new Image(s);
                playBtn.setImage(image);
            }else if (musicPlayer.getStatus() == MediaPlayer.Status.PAUSED){
                //修改图标 点击完是播放状态。
                musicPlayer.play();
                s = getClass().getResource("img/stop.png").toExternalForm();
                Image image = new Image(s);
                playBtn.setImage(image);
            }
        }
    }


    public void click_nextBtn(){
        System.out.println("release");
        System.out.println("click");
        if(path == null){
            return;
        }
        if(type!=1){
            if(musicList.size()==0) return;
            //初始化播放器
            if(musicPlayer == null){
                currentMusic = 0;
                init_musicPlayer(musicList.getMedia(0));
                viewList.getSelectionModel().select(0);
                String s = getClass().getResource("img/stop.png").toExternalForm();
                Image image = new Image(s);
                playBtn.setImage(image);
                musicPlayer.setRate(1.0);
                endtime=System.currentTimeMillis();
                if(endtime-starttime>500){
                    return;
                }
                //clickSomething(playBtn);
                return;
            }
            //释放当前Media资源
//        musicPlayer.stop();
//        musicPlayer.dispose();
            //加载下一首资源，播放
            //Media media;//get()

            musicPlayer.setRate(1.0);
            endtime=System.currentTimeMillis();
            if(endtime-starttime>500){
                return;
            }
            if(loopWay==0 || loopWay ==1 ){
                //System.out.println((currentMusic+1)%musicList.size());
                //media = musicList.getMedia((currentMusic+1)%musicList.size());
                currentMusic = (currentMusic+1)%musicList.size();
                //musicPlayer = new MediaPlayer(media);
                viewList.getSelectionModel().select((currentMusic));
                //musicPlayer.play();
                String s = getClass().getResource("img/stop.png").toExternalForm();
                Image image = new Image(s);
                playBtn.setImage(image);
                //clickSomething(playBtn);
            }
//        else if(loopWay==1){
//            media = musicList.getMedia(currentMusic);
//            musicPlayer = new MediaPlayer(media);
//            musicPlayer.play();
//            String s = getClass().getResource("img/stop.png").toExternalForm();
//            Image image = new Image(s);
//            playBtn.setImage(image);
//            //clickSomething(playBtn);
//        }
            else if(loopWay==2){
                //media = musicList.getRandomMedia(currentMusic);
//            currentMusic = musicList.getIndex(media);
//            musicPlayer = new MediaPlayer(media);
                Random t=new Random();
                int i;
                do{
                    i=t.nextInt(musicList.size());
                }while(currentMusic==i);
                currentMusic = i;
                viewList.getSelectionModel().select(currentMusic);
//            musicPlayer.play();
                String s = getClass().getResource("img/stop.png").toExternalForm();
                Image image = new Image(s);
                playBtn.setImage(image);
                //clickSomething(playBtn);
            }}else{
                if(videoList.size()==0) return;
                //初始化播放器
                if(musicPlayer == null){
                    currentMusic = 0;
                    init_musicPlayer(videoList.getMedia(0));
                    viewList.getSelectionModel().select(0);
                    String s = getClass().getResource("img/stop.png").toExternalForm();
                    Image image = new Image(s);
                    playBtn.setImage(image);
                    musicPlayer.setRate(1.0);
                    Mediaview=new MediaView(musicPlayer);
                    Mediaview.setFitHeight(660);
                    Mediaview.setFitWidth(660);
                    Mediaview.setY(50);
                    ap.getChildren().add(Mediaview);
                    endtime=System.currentTimeMillis();
                    if(endtime-starttime>100){
                        return;
                    }
                    //clickSomething(playBtn);
                    return;
                }
                //释放当前Media资源
//        musicPlayer.stop();
//        musicPlayer.dispose();
                //加载下一首资源，播放
                //Media media;//get()

                musicPlayer.setRate(1.0);
                endtime=System.currentTimeMillis();
                if(endtime-starttime>100){
                    return;
                }
                if(loopWay==0 || loopWay ==1 ){
                    //System.out.println((currentMusic+1)%musicList.size());
                    //media = musicList.getMedia((currentMusic+1)%musicList.size());
                    currentMusic = (currentMusic+1)%videoList.size();
                    //musicPlayer = new MediaPlayer(media);
                    viewList.getSelectionModel().select((currentMusic));
                    //musicPlayer.play();
                    String s = getClass().getResource("img/stop.png").toExternalForm();
                    Image image = new Image(s);
                    Mediaview=new MediaView(musicPlayer);
                    Mediaview.setFitHeight(660);
                    Mediaview.setFitWidth(660);
                    Mediaview.setY(50);
                    ap.getChildren().add(Mediaview);
                    playBtn.setImage(image);
                    //clickSomething(playBtn);
                }
//        else if(loopWay==1){
//            media = musicList.getMedia(currentMusic);
//            musicPlayer = new MediaPlayer(media);
//            musicPlayer.play();
//            String s = getClass().getResource("img/stop.png").toExternalForm();
//            Image image = new Image(s);
//            playBtn.setImage(image);
//            //clickSomething(playBtn);
//        }
                else if(loopWay==2){
                    //media = musicList.getRandomMedia(currentMusic);
//            currentMusic = musicList.getIndex(media);
//            musicPlayer = new MediaPlayer(media);
                    Random t=new Random();
                    int i;
                    do{
                        i=t.nextInt(videoList.size());
                    }while(currentMusic==i);
                    currentMusic = i;
                    viewList.getSelectionModel().select(currentMusic);
//            musicPlayer.play();
                    String s = getClass().getResource("img/stop.png").toExternalForm();
                    Image image = new Image(s);
                    playBtn.setImage(image);
                    Mediaview=new MediaView(musicPlayer);
                    Mediaview.setFitHeight(660);
                    Mediaview.setFitWidth(660);
                    Mediaview.setY(50);
                    ap.getChildren().add(Mediaview);
                    //clickSomething(playBtn);
                }
            }
        }


    public void press_nextBtn(){
        System.out.println("press");
        if(musicPlayer==null){
            return;
        }
        starttime=System.currentTimeMillis();
        musicPlayer.setRate(1.5);
    }

    public void release_nextBtn(){
    }

    public void click_previousBtn(){

        if(path == null)
            return;
        if(type!=1){
            if(musicList.size()==0) return;
            //初始化播放器
            if(musicPlayer == null){
                currentMusic = musicList.size()-1;
                init_musicPlayer(musicList.getMedia(currentMusic));
                viewList.getSelectionModel().select(currentMusic);
                //musicPlayer.play();
                String s = getClass().getResource("img/stop.png").toExternalForm();
                Image image = new Image(s);
                playBtn.setImage(image);
                this.pusher.cancel();
                endtime=System.currentTimeMillis();
                if(endtime-starttime>100){
                    return;
                }
                //clickSomething(playBtn);
                return;
            }
            //释放当前Media资源
//        musicPlayer.stop();
//        musicPlayer.dispose();
//        System.out.println(currentMusic);
            //加载上一首资源，播放
//        Media media =null;//get()
            this.pusher.cancel();
            endtime=System.currentTimeMillis();
            if(endtime-starttime>100){
                return;
            }
            if(loopWay == 0 || loopWay == 1){
                currentMusic = (currentMusic-1+ musicList.size())%musicList.size();
                viewList.getSelectionModel().select(currentMusic);
//            media = musicList.getMedia(currentMusic);
//            musicPlayer = new MediaPlayer(media);
//            musicPlayer.play();
                String s = getClass().getResource("img/stop.png").toExternalForm();
                Image image = new Image(s);
                playBtn.setImage(image);
            }
//        else if(loopWay == 1){
//            media = musicList.getMedia(currentMusic);
//            musicPlayer = new MediaPlayer(media);
//            clickSomething(playBtn);
//        }
            else if(loopWay == 2){
//            media = musicList.getRandomMedia(currentMusic);
//            currentMusic = musicList.getIndex(media);
                Random t=new Random();
                int i;
                do{
                    i=t.nextInt(musicList.size());
                }while(currentMusic==i);
                currentMusic = i;
                viewList.getSelectionModel().select(currentMusic);
//            musicPlayer.play();
                String s = getClass().getResource("img/stop.png").toExternalForm();
                Image image = new Image(s);
                playBtn.setImage(image);
                //clickSomething(playBtn);
            }
            //musicPlayer = new MediaPlayer(media);
        }else{
            if(videoList.size()==0) return;
            //初始化播放器
            if(musicPlayer == null){
                currentMusic = videoList.size()-1;
                init_musicPlayer(videoList.getMedia(currentMusic));
                viewList.getSelectionModel().select(currentMusic);
                //musicPlayer.play();
                String s = getClass().getResource("img/stop.png").toExternalForm();
                Image image = new Image(s);
                playBtn.setImage(image);
                Mediaview=new MediaView(musicPlayer);
                Mediaview.setFitHeight(660);
                Mediaview.setFitWidth(660);
                Mediaview.setY(50);
                ap.getChildren().add(Mediaview);
                this.pusher.cancel();
                endtime=System.currentTimeMillis();
                if(endtime-starttime>100){
                    return;
                }
                //clickSomething(playBtn);
                return;
            }
            //释放当前Media资源
//        musicPlayer.stop();
//        musicPlayer.dispose();
//        System.out.println(currentMusic);
            //加载上一首资源，播放
//        Media media =null;//get()
            this.pusher.cancel();
            endtime=System.currentTimeMillis();
            if(endtime-starttime>100){
                return;
            }
            if(loopWay == 0 || loopWay == 1){
                currentMusic = (currentMusic-1+ videoList.size())%videoList.size();
                viewList.getSelectionModel().select(currentMusic);
//            media = musicList.getMedia(currentMusic);
//            musicPlayer = new MediaPlayer(media);
//            musicPlayer.play();
                String s = getClass().getResource("img/stop.png").toExternalForm();
                Image image = new Image(s);
                playBtn.setImage(image);
                Mediaview=new MediaView(musicPlayer);
                Mediaview.setFitHeight(660);
                Mediaview.setFitWidth(660);
                Mediaview.setY(50);
                ap.getChildren().add(Mediaview);
            }
//        else if(loopWay == 1){
//            media = musicList.getMedia(currentMusic);
//            musicPlayer = new MediaPlayer(media);
//            clickSomething(playBtn);
//        }
            else if(loopWay == 2){
//            media = musicList.getRandomMedia(currentMusic);
//            currentMusic = musicList.getIndex(media);
                Random t=new Random();
                int i;
                do{
                    i=t.nextInt(videoList.size());
                }while(currentMusic==i);
                currentMusic = i;
                viewList.getSelectionModel().select(currentMusic);
//            musicPlayer.play();
                String s = getClass().getResource("img/stop.png").toExternalForm();
                Image image = new Image(s);
                playBtn.setImage(image);
                Mediaview=new MediaView(musicPlayer);
                Mediaview.setFitHeight(660);
                Mediaview.setFitWidth(660);
                Mediaview.setY(50);
                ap.getChildren().add(Mediaview);
                //clickSomething(playBtn);
            }
            //musicPlayer = new MediaPlayer(media);
        }
    }

    public void press_previousBtn(){
        System.out.println("press");
        if(musicPlayer==null){
            return;
        }
        starttime=System.currentTimeMillis();
        this.pusher=new Timer();
        TimerTask pushing=new TimerTask() {
            @Override
            public void run() {
                musicPlayer.seek(new Duration(musicPlayer.getCurrentTime().toMillis()-120));
            }
        };
        pusher.schedule(pushing,0,70);
    }

    public void click_loopMethod(){
        String s = "";
        Image image;
        if(loopWay == 0){
            s = getClass().getResource("img/singleLoop.png").toExternalForm();

        }else if(loopWay == 1){
            s = getClass().getResource("img/randomLoop.png").toExternalForm();

        }else if(loopWay == 2){
            s = getClass().getResource("img/listLoop.png").toExternalForm();

        }
        image = new Image(s);
        loopMethod.setImage(image);
        loopWay = (loopWay + 1) % 3;
    }

    public void click_voice(){
        if(musicPlayer==null)
            return;
        String s;
        if(musicPlayer.isMute()){
            //设置图标
            s = getClass().getResource("img/voice.png").toExternalForm();
            Image image = new Image(s);
            voice.setImage(image);
            musicPlayer.setMute(false);
            currentVolume = musicPlayer.getVolume()*100;
            volumeSlider.setValue(currentVolume);
        }
        else{
            //设置图标
            s = getClass().getResource("img/NoVoice.png").toExternalForm();
            Image image = new Image(s);
            voice.setImage(image);
            musicPlayer.setMute(true);
            volumeSlider.setValue(0);
        }
    }

    public void directoryChoosing(){
        DirectoryChooser dc = new DirectoryChooser();
        dc.setTitle("选择一个文件夹");
        dc.setInitialDirectory(new File("D:" + File.separator));
        File file = dc.showDialog(new Stage());
        if (file == null) return;
//        if(path != null){
//            //处理当前列表中有数据
//            if (musicPlayer != null) musicPlayer.dispose();
//            musicList = null;
//            currentMusic = -1;
//            allTime.setText("");
//            currentTime.setText("");
//        }
        setPath(file.getAbsolutePath());
    }

    public void init_VolumeSlider(){
        volumeSlider.valueProperty().addListener(new ChangeListener<Number>() {
            @Override
            public void changed(ObservableValue<? extends Number> observableValue, Number old_val, Number new_val) {
                if(Math.abs(old_val.doubleValue() - 0) < 0.000000002){
                    //若旧值为0，给voice换图片，把currentVolume赋新值，设置mp音量。
                    String s = getClass().getResource("img/voice.png").toExternalForm();
                    Image image = new Image(s);
                    voice.setImage(image);
                    currentVolume = new_val.doubleValue();
                    if (path == null) return;
                    musicPlayer.setMute(false);
                    musicPlayer.setVolume(currentVolume/100);
                }else if(Math.abs(new_val.doubleValue()-0) < 0.000000002){
                    //若新值为0，给voice换图片，把currentVolume赋值，设置mp音量。
                    String s = getClass().getResource("img/NoVoice.png").toExternalForm();
                    Image image = new Image(s);
                    voice.setImage(image);
                    if (path == null) return;
                    musicPlayer.setMute(true);
                    //mediaPlayer.setVolume(0);
                }else{
//                    System.out.println(old_val);
//                    System.out.println(new_val);
                    currentVolume = new_val.doubleValue();
                    if (path == null) return;
                    musicPlayer.setVolume(currentVolume/100);
                }
            }
        });
    }

    public void init_listView(){
        if(type!=1){
            if(musicList==null||musicList.size()==0){
                if(musicPlayer != null)
                    viewList.getItems().clear();
                    mediaSlider.setValue(0);
                    allTime.setText("");
                    currentTime.setText("");
                    songName.setText("Welcome !");
                    artistName.setText(" ");
                    String s = getClass().getResource("img/start.png").toExternalForm();
                    Image image = new Image(s);
                    playBtn.setImage(image);
                    mediaSlider.setDisable(true);
                    dialog(null,"路径内无歌曲");
                    System.out.println("路径内无歌曲");
           }else{
                init_view(musicList);
            }
        }else {
            if(videoList==null||videoList.size() == 0){
                viewList.getItems().clear();
                mediaSlider.setValue(0);
                allTime.setText("");
                currentTime.setText("");
                songName.setText("Welcome !");
                artistName.setText(" ");
                String s = getClass().getResource("img/start.png").toExternalForm();
                Image image = new Image(s);
                playBtn.setImage(image);
                mediaSlider.setDisable(true);
                dialog(null,"路径内无视频");
                System.out.println("路径内无视频");
            }else{
                init_view(videoList);
            }
        }
    }

    private void init_view(MediaList mediaList){
        LinkedList<MediaEntity> mediaEntityList = mediaList.getMediaEntityList();
        folderFlag = true;
        mediaSlider.setValue(0);
        allTime.setText("");
        currentTime.setText("");
        songName.setText("Welcome !");
        artistName.setText(" ");
        String s = getClass().getResource("img/start.png").toExternalForm();
        Image image = new Image(s);
        playBtn.setImage(image);
        currentMusic = -1;
        musicPlayer = null;
        observableList.clear();
        observableList.addAll(mediaEntityList);
        if(currentMusic != -1){
            //当前有歌曲在播放（有listview被选中）
            musicPlayer.dispose();
//            spectrumData.init();
            if(rt==null)
                init_albumView();
            rt.jumpTo(Duration.ZERO);
            rt.stop();
            for(int i=0;i<spectrumData.getRectangle_num();i++){
                ap.getChildren().remove(spectrumData.rectangles[i]);
            }
            String s1 = getClass().getResource("img/music.png").toExternalForm();
            Image image1 = new Image(s1);
            albumImg.setImage(image1);

//            for (int i = 0; i < 40; i++) {
//                spectrumData.rectangles[i].setHeight(0);
//            }
//            String s = getClass().getResource("img/start.png").toExternalForm();
//            Image image = new Image(s);
//            playBtn.setImage(image);
        }

        //strList = FXCollections.observableArrayList(mediaEntityList);

        //viewList.setItems(observableList);
        //自定义ListCell
        viewList.setCellFactory(new Callback<ListView<MediaEntity>, ListCell<MediaEntity>>() {
            @Override
            public ListCell<MediaEntity> call(ListView<MediaEntity> mediaEntityListView) {
                return new MediaCell();
            }
        });
        viewList.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<MediaEntity>() {
            @Override
            public void changed(ObservableValue<? extends MediaEntity> observableValue, MediaEntity old_val, MediaEntity new_val) {
                //System.out.println("from "+old_val.getName()+" to "+new_val.getName());
                //如果是正在切换文件夹，就立刻返回。
                if(folderFlag)
                    return;
                if (musicPlayer != null) {
                    //musicPlayer.stop();
                    musicPlayer.dispose();
                    if(type!=1&&musicPlayer!=null){
                        if(rt!=null)
                        rt.pause();
                        spectrumData.init();
                    }
                }

                //musicPlayer = new MediaPlayer(new_val.getMedia());
                if(type!=1)
                    currentMusic = musicList.getIndex(new_val.getMedia());
                else{
                    if(new_val!=null)
                    currentMusic = videoList.getIndex(new_val.getMedia());
                }

                init_musicPlayer(new_val.getMedia());
                System.out.println(new_val);

                musicPlayer.play();
                if(type==0&&rt!=null)
                    rt.play();
                String s = getClass().getResource("img/stop.png").toExternalForm();
                Image image = new Image(s);
                playBtn.setImage(image);
                if(type==1){
                    Mediaview=new MediaView(musicPlayer);
                    Mediaview.setFitHeight(660);
                    Mediaview.setFitWidth(660);
                    Mediaview.setY(50);
                    ap.getChildren().add(Mediaview);
                }

                //clickSomething(playBtn);
            }
        });
        folderFlag = false;
    }


    //模式选择
    public void init_ComboBox(){
        mediaType.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() {
            @Override
            public void changed(ObservableValue<? extends String> observableValue, String old_val, String new_val) {
                folderFlag=true;
                if(Mediaview!=null)
                    Mediaview.setVisible(false);
                if(musicPlayer!=null){
                    musicPlayer.dispose();
                    if(type==0){
                        if(rt==null)
                            init_albumView();
                        rt.jumpTo(Duration.ZERO);
                        rt.stop();
                        for(int i=0;i< spectrumData.getRectangle_num();i++)
                            ap.getChildren().remove(spectrumData.rectangles[i]);
                        String s1 = getClass().getResource("img/music.png").toExternalForm();
                        Image image1 = new Image(s1);
                        albumImg.setImage(image1);
                        if(Mediaview!=null)
                            Mediaview.setVisible(false);
                    }else{
                        Mediaview.setVisible(true);
                    }
                }
                type = new_val.equals("音频") ? 0 : 1;
//                System.out.println(type);
                if(path==null){
                    folderFlag = false;
                    return;
                }
                observableList.clear();
                observableList=viewList.getItems();
                //setPath(path);
                init_listView();
            }
        });
    }

    /**当选择了某一路径时触发*/
    public void init_MediaList(){
        if(type!=1){    //音频
            musicList = new MediaList();
            musicList.init(this.path, "mp3");
        }else {         //视频
            videoList = new MediaList();
            videoList.init(this.path,"mp4");
        }

        init_listView();
//        currentMusic = -1;
    }

    private void init_musicPlayer(Media media){
        musicPlayer = new MediaPlayer(media);

        currentVolume = volumeSlider.getValue();

        musicPlayer.setVolume(currentVolume/100);
        musicPlayer.setOnEndOfMedia(new Runnable() {
            @Override
            public void run() {
                if(type!=1){
                    if(musicList.size()==1){
                        musicPlayer.seek(Duration.ZERO);
                        return;
                    }
                    if(loopWay == 0){
                        musicPlayer.dispose();
                        spectrumData.init();
                        currentMusic = (currentMusic+1)%musicList.size();
                        viewList.getSelectionModel().select((currentMusic));
                        String s = getClass().getResource("img/stop.png").toExternalForm();
                        Image image = new Image(s);
                        playBtn.setImage(image);
                    } else if(loopWay == 1){
                        musicPlayer.seek(Duration.ZERO);
                        //musicPlayer.play();
                    } else if(loopWay == 2){
                        musicPlayer.dispose();
                        spectrumData.init();
                        Random t=new Random();
                        int i;
                        do{
                            i=t.nextInt(musicList.size());
                        }while(currentMusic==i);
                        currentMusic = i;
                        viewList.getSelectionModel().select(currentMusic);
                        String s = getClass().getResource("img/stop.png").toExternalForm();
                        Image image = new Image(s);
                        playBtn.setImage(image);
                    }else{
                        if(musicList.size()==1){
                            musicPlayer.seek(Duration.ZERO);
                            return;
                        }
                        if(loopWay == 0){
                            musicPlayer.dispose();
                            spectrumData.init();
                            currentMusic = (currentMusic+1)%musicList.size();
                            viewList.getSelectionModel().select((currentMusic));
                            String s = getClass().getResource("img/stop.png").toExternalForm();
                            Image image = new Image(s);
                            playBtn.setImage(image);
                        } else if(loopWay == 1){
                            musicPlayer.seek(Duration.ZERO);
                            //musicPlayer.play();
                        } else if(loopWay == 2){
                            musicPlayer.dispose();
                            spectrumData.init();
                            Random t=new Random();
                            int i;
                            do{
                                i=t.nextInt(musicList.size());
                            }while(currentMusic==i);
                            currentMusic = i;
                            viewList.getSelectionModel().select(currentMusic);
                            String s = getClass().getResource("img/stop.png").toExternalForm();
                            Image image = new Image(s);
                            playBtn.setImage(image);
                        }
                    }
                }else{
                    if(videoList.size()==1){
                        musicPlayer.seek(Duration.ZERO);
                        return;
                    }
                    if(loopWay == 0){
                        if(musicPlayer!=null)
                        musicPlayer.dispose();
                        currentMusic = (currentMusic+1)%videoList.size();
                        viewList.getSelectionModel().select((currentMusic));
                        String s = getClass().getResource("img/stop.png").toExternalForm();
                        Image image = new Image(s);
                        playBtn.setImage(image);
                        Mediaview=new MediaView(musicPlayer);
                        Mediaview.setFitHeight(660);
                        Mediaview.setFitWidth(660);
                        Mediaview.setY(50);
                        ap.getChildren().add(Mediaview);
                    } else if(loopWay == 1){
                        musicPlayer.seek(Duration.ZERO);
                        //musicPlayer.play();
                    } else if(loopWay == 2){
                        musicPlayer.dispose();
                        Random t=new Random();
                        int i;
                        do{
                            i=t.nextInt(videoList.size());
                        }while(currentMusic==i);
                        currentMusic = i;
                        viewList.getSelectionModel().select(currentMusic);
                        String s = getClass().getResource("img/stop.png").toExternalForm();
                        Image image = new Image(s);
                        playBtn.setImage(image);
                        Mediaview=new MediaView(musicPlayer);
                        Mediaview.setFitHeight(660);
                        Mediaview.setFitWidth(660);
                        Mediaview.setY(50);
                        ap.getChildren().add(Mediaview);
                    }else{
                        if(videoList.size()==1){
                            musicPlayer.seek(Duration.ZERO);
                            return;
                        }
                        if(loopWay == 0){
                            musicPlayer.dispose();
                            currentMusic = (currentMusic+1)%videoList.size();
                            viewList.getSelectionModel().select((currentMusic));
                            String s = getClass().getResource("img/stop.png").toExternalForm();
                            Image image = new Image(s);
                            playBtn.setImage(image);
                            Mediaview=new MediaView(musicPlayer);
                            Mediaview.setFitHeight(660);
                            Mediaview.setFitWidth(660);
                            Mediaview.setY(50);
                            ap.getChildren().add(Mediaview);
                        } else if(loopWay == 1){
                            musicPlayer.seek(Duration.ZERO);
                            //musicPlayer.play();
                        } else if(loopWay == 2){
                            musicPlayer.dispose();
                            Random t=new Random();
                            int i;
                            do{
                                i=t.nextInt(videoList.size());
                            }while(currentMusic==i);
                            currentMusic = i;
                            viewList.getSelectionModel().select(currentMusic);
                            String s = getClass().getResource("img/stop.png").toExternalForm();
                            Image image = new Image(s);
                            playBtn.setImage(image);
                            Mediaview=new MediaView(musicPlayer);
                            Mediaview.setFitHeight(660);
                            Mediaview.setFitWidth(660);
                            Mediaview.setY(50);
                            ap.getChildren().add(Mediaview);
                        }
                    }
                }
            }
        });
        init_mediaSlider();

        if(type!=1){
            init_SpectrumData();
            init_albumView();
        }
            init_Labels();
        }


    private void init_mediaSlider(){
        mediaSlider.setDisable(false);

        //设置当前时间。
        musicPlayer.setOnReady(new Runnable() {
            @Override
            public void run() {
                mediaSlider.setMin(0);
                mediaSlider.setValue(0);
                currentTime.setText(String.format("%.2f", 0.0));
                allTime.setText(getFormatTime((int)(musicPlayer.getTotalDuration().toSeconds())));
                mediaSlider.setMax(musicPlayer.getTotalDuration().toMinutes());
            }
        });

        //音乐播放时，进度条动
        musicPlayer.currentTimeProperty().addListener(new ChangeListener<Duration>() {
            @Override
            public void changed(ObservableValue<? extends Duration> observableValue, Duration old_val, Duration new_val) {
                if (!sliderFlag){
                    mediaSlider.setValue(new_val.toMinutes());
                }
                currentTime.setText(getFormatTime((int)new_val.toSeconds()));
            }
        });
        //进度条动拖时，音乐跳
//        mediaSlider.valueProperty().addListener(new ChangeListener<Number>() {
//            @Override
//            public void changed(ObservableValue<? extends Number> observableValue, Number old_val, Number new_val) {
//                if(sliderFlag)
//                    musicPlayer.seek(Duration.minutes(new_val.doubleValue()));
//            }
//        });

        mediaSlider.setOnMousePressed(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent mouseEvent) {
                sliderFlag = true;

            }
        });

        mediaSlider.setOnMouseReleased(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent mouseEvent) {
                sliderFlag = false;
                musicPlayer.seek(Duration.minutes(mediaSlider.getValue()));
            }
        });
    }

    public BottomController(){
        //初始化变量
        type = 0;
        currentMusic = -1;
        loopWay = 0;
        //1.如果之前有听过歌，打开应该MediaPlayer中应该是上次的位置。
//        File file = new File("E:\\CloudMusic\\Linda Rosenthal - Csardas (Vittorio Monti).mp3");
//        Media media = new Media(file.toURI().toString());
//        musicPlayer = new MediaPlayer(media);
        //2.初始化当前音量
        currentVolume = 0.1;
        path = null;
//        musicList = new MediaList();
//        videoList = new MediaList();
//        musicPlayer.setVolume(0.1);
        //path = "E:\\CloudMusic";
    }


    //根据type不同判断文件
    public void setPath(String path){
        mediaSlider.setDisable(true);
        if(type!=1){
            LinkedList<String> linkedList = MediaList.detectFile(path,"mp3");
            if(linkedList.size()==0) {
                //没有数据，直接返回。

                dialog(null,"路径内无歌曲");
                System.out.println("路径内无歌曲");
                return;
            }
            this.path = path;
            songName.setText("");
            init_MediaList();
        }else{
            LinkedList<String> linkedList = MediaList.detectFile(path,"mp4");
            if(linkedList.size()==0) {
                //没有数据，直接返回。

                dialog(null,"路径内无视频");
                System.out.println("路径内视频");
                return;
            }

            this.path = path;
            init_MediaList();
        }

    }

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        init_VolumeSlider();
        init_ComboBox();
        observableList = viewList.getItems();
        //实际操纵observablelist可以改变播放列表

        mediaType.setBackground(new Background(new BackgroundFill(Color.valueOf("#00000000"),null,null)));
        viewList.setBackground(new Background(new BackgroundFill(Color.valueOf("#00000000"),null,null)));
        viewList.setOpacity(0.7);
        ImageView iv = new ImageView();
        iv.setEffect(new GaussianBlur(20));
        leftVBox.getChildren().add(iv);
        leftVBox.setStyle("-fx-background-color: #ffffff99");
        topHBox.getChildren().add(iv);
        topHBox.setStyle("-fx-background-color: #ffffff99");

        bottomPane.getChildren().add(iv);
        bottomPane.setStyle("-fx-background-color: #ffffff99");


        String s = getClass().getResource("img/bgd1.jpg").toExternalForm();
        Image image = new Image(s);
        BackgroundSize size = new BackgroundSize(BackgroundSize.AUTO, BackgroundSize.AUTO, true, true, true, true);

        //System.out.println(image);
        Background background = new Background(new BackgroundImage(image,
                BackgroundRepeat.NO_REPEAT,
                BackgroundRepeat.NO_REPEAT,
                BackgroundPosition.CENTER,
                size));

        rootPane.setBackground(background);
        //oprootPane.setEffect(new GaussianBlur(20));

    }

    private void clickSomething(Node node){
        node.fireEvent(new MouseEvent(MouseEvent.MOUSE_CLICKED, 0, // double x,
                0, // double y,
                0, // double screenX,
                0, // double screenY,
                MouseButton.PRIMARY, // MouseButton button,
                0, // int clickCount,
                false, // boolean shiftDown,
                false, // boolean controlDown,
                false, // boolean altDown,
                false, // boolean metaDown,
                true, // boolean primaryButtonDown,
                false, // boolean middleButtonDown,
                false, // boolean secondaryButtonDown,
                false, // boolean synthesized,
                false, // boolean popupTrigger,
                false, // boolean stillSincePress,
                null // PickResult pickResult
        ));
    }

    private String getFormatTime(Integer totalSeconds){
        if (totalSeconds == null || totalSeconds < 1) {
            return "00:01";
        }
        //将秒格式化成HH:mm:ss
        //这里应该用Duration更合理，但它不能格式化成字符串
        //而使用LocalTime，在时间超过24小时后格式化也会有问题（！）
        int hours = totalSeconds / 3600;

        int rem = totalSeconds % 3600;
        int minutes = rem / 60;
        int seconds = rem % 60;
        if (hours <= 0) {
            return String.format("%02d:%02d", minutes, seconds);
        }
        return String.format("%02d:%02d:%02d", hours, minutes, seconds);
    }

    private void dialog(String title,String text){
        if (title == null) title = "提示";
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(text);
        alert.showAndWait();
    }

    private void init_SpectrumData(){
        spectrumData = new SpectrumData(ap);
        musicPlayer.setAudioSpectrumListener(new AudioSpectrumListener() {
            @Override
            public void spectrumDataUpdate(double timestamp, double duration, float[] magnitudes, float[] phases) {
                spectrumData.updateRectangles(magnitudes);
            }
        });
    }

    private void init_albumView(){
        MP3Entity mp3Entity = (MP3Entity)musicList.getMediaEntityList().get(currentMusic);
        String s = mp3Entity.getAPICPath();
        //System.out.println("path:"+s);
        if(s ==null){
            s = getClass().getResource("img/music.png").toExternalForm();
            Image image = new Image(s);
            albumImg.setImage(image);
            return;
        }
        s="file:\\"+s;
//        System.out.println(s);
        Image image = new Image(s);
        albumImg.setImage(image);

        //旋转动画

        rt = new RotateTransition();
        rt.setCycleCount(Animation.INDEFINITE);
        rt.setInterpolator(Interpolator.LINEAR);
        rt.setDuration(Duration.seconds(26));
        rt.setFromAngle(0);
        rt.setByAngle(360);
        rt.setNode(albumImg);
//        musicPlayer.setOnPaused(new Runnable() {
//            @Override
//            public void run() {
//                rt.pause();
//            }
//        });
    }
    /**初始化歌名、歌手*/
    private void init_Labels() {
        if (type != 1) {
            songName.setText(musicList.getMediaEntityList().get(currentMusic).getName());
            artistName.setText(musicList.getMediaEntityList().get(currentMusic).getArtist());
            artistName.setDisable(false);
        } else {
            songName.setText(videoList.getMediaEntityList().get(currentMusic).getName());
            artistName.setDisable(true);
        }
    }
    public void help_about(){
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setHeaderText("Media Player !");
        alert.setContentText("""
                版本: 1.67.1 (user setup)
                日期: 2022-05-06T12:37:03.389Z
                Electron: 17.4.1
                Chromium: 98.0.4758.141
                Node.js: 16.13.0
                V8: 9.8.177.13-electron.0
                OS: Windows_NT x64 10.0.19044""");
        alert.showAndWait();
    }


}
class MediaCell extends ListCell<MediaEntity>{
    @Override
    protected void updateItem(MediaEntity mediaEntity, boolean b) {
        super.updateItem(mediaEntity, b);
//        if(b)  return;
        if(b || mediaEntity == null){
            setText(null);
            setGraphic(null);
            return;
        }
//        System.out.println(mediaEntity);
        Pane pane = new Pane();

        pane.setPadding(new Insets(0));
        pane.setPrefHeight(30);
        pane.setPrefWidth(200);

        Label numLabel = new Label();
        numLabel.setLayoutX(0);
        numLabel.setLayoutY(0);
//        numLabel.setStyle("-fx-background-color: green");
        numLabel.setAlignment(Pos.CENTER_LEFT);
        numLabel.setTextAlignment(TextAlignment.LEFT);
//        numLabel.setTextAlignment(TextAlignment.);
        numLabel.setPrefHeight(30);
        numLabel.setPrefWidth(30);
        numLabel.setPadding(new Insets(0,0,0,5));
        numLabel.setFont(new Font(10));
        numLabel.setText("" + (getIndex() + 1));

        Label nameLabel = new Label();
        nameLabel.setLayoutX(40);
        nameLabel.setLayoutY(0);
        nameLabel.setTextAlignment(TextAlignment.CENTER);
        nameLabel.setPrefHeight(30);
        nameLabel.setPrefWidth(170);
        nameLabel .setText(mediaEntity.getName());
        numLabel.setBackground(new Background(new BackgroundFill(Color.valueOf("#00000000"),null,null)));
        nameLabel.setBackground(new Background(new BackgroundFill(Color.valueOf("#00000000"),null,null)));
        pane.getChildren().add(numLabel);
        pane.getChildren().add(nameLabel);
        Tooltip.install(nameLabel,new Tooltip(nameLabel.getText()));
        nameLabel.setTextOverrun(OverrunStyle.ELLIPSIS);

        //pane.setBackground(new Background(new BackgroundFill(Color.valueOf("#B6A2D7"),null,null)));

        setGraphic(pane);
    }
}

